/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { isFunction } from 'lodash';
import React from 'react';
import { useCacheId } from './_utils';
import { Form } from 'antd';
import ProForm from '@ant-design/pro-form';

interface KeepAliveProps {
  cacheId: string;
}

/**
 *
 * @description
 * 注意：
 * 1、initialValues会被缓存替换，所以在form.resetFields会出现非预期效果；
 * 2、需要实现重置需要手动设置 form.setFieldsValue(defaultValues) ；
 * 3、目前仅实现表单组件的缓存 Form|ProForm ；
 * @param props
 * @returns
 */
const KeepAlive: React.FC<KeepAliveProps> = (props) => {
  const { cacheId: propsCacheId } = props;
  const { getCache, setCache } = useCacheId(propsCacheId);

  return (
    <>
      {React.Children.map(props.children, (child) => {
        if (React.isValidElement(child)) {
          const childType = child.type;
          // 目前仅支持表单组件
          if (isFunction(childType) && (childType === Form || childType === ProForm)) {
            const { initialValues, onFinish } = child.props;
            return React.cloneElement<any>(child, {
              initialValues: {
                ...initialValues,
                ...getCache(),
              },
              onFinish: (values: any) => {
                // 缓存记录
                setCache(values);
                if (isFunction(onFinish)) {
                  onFinish(values);
                }
              },
            });
          }
        }
        return child;
      })}
    </>
  );
};

export default KeepAlive;
